package com.huikeportal.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huikeportal.controller.common.Lang;
import com.huikeportal.model.ChangeGcParam;
import com.huikeportal.model.Language;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteSelectParam;
import com.huikeportal.model.SiteSimpleInfo;
import com.huikeportal.model.SquareChange;
import com.huikeportal.model.TodayIndexes;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.TodayIndexesService;

@Controller
@Scope("prototype")
public class ComparativeAnalysisController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;
	
	@Autowired
	private TodayIndexesService todayIndexesService;

	@Autowired
	SelectSiteService selectSiteService;
	
	@RequestMapping("/comparativeAnalysis")
	public String comparativeAnalysis(ModelMap model,String siteId,HttpServletRequest request,HttpServletResponse response) throws Exception {

		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo=loginService.getUserInfo(userInfo);
		 String userId = userInfo.getUserId();
		//获取当前系统语言
        String sysLang = session.getAttribute("sysLang").toString();
        //查询当前页面id
        SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString("comparativeAnalysis");
        Integer menuId = selectSiteService.getMenuId(sql);
        //获取用户权限按钮信息
        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
                userId, menuId);
        
        String buttonExport = "0";
        for(WordBook wordBook:buttonList){
        	if("导出".equals(wordBook.getDicValue())){
        		buttonExport = "1";
        		break;
        	}
        }
       
        /** 选择场所初始化 **/
		// 更换广场div初始化数据
		List<SiteAllInfo> dpGcList = loginService.getDpGcSiteList(userInfo);
		ChangeGcParam changeGcParam = new ChangeGcParam();
		changeGcParam.setSelectType("1");// 多选场所
		List<SiteAllInfo> yuanGcList = loginService.getGcSiteList(userInfo);
		SquareChange squareChange = selectSiteService.squareChangeLoad(
				changeGcParam, dpGcList,yuanGcList);// 获取初始化更换广场信息
		model.addAttribute("squareChange", squareChange);// 更换广场数据初始化
		model.addAttribute("selectType", changeGcParam.getSelectType());// 选择类型，1为多选
		model.addAttribute("pageType", "0");// 页面类型，带集团，0表示不带集团
		model.addAttribute("backPage", "comparativeAnalysis");// 返回地址
		// 初始化查询集团&地区列表
		SqlParameter sqlParam = new SqlParameter();
		sqlParam.setString(userInfo.getUserId());
		List<SiteAllInfo> jtDqList = selectSiteService.getJtDqList(sqlParam);
		model.addAttribute("jtDqList", jtDqList);
		if (siteId != null && !"".equals(siteId)) {
			// 根据场所id查询场所信息
			List<SiteSimpleInfo> selectedSiteList = selectSiteService
					.getSimpleSiteList(siteId);
			// 将已选择的场所传回到页面上
			model.addAttribute("selectedSiteList", JSONArray.fromObject(
					selectedSiteList).toString());
		} 

		
		String siteType=FootfallConstant.WHOLE_SITETYPE;//场所类型是300
		SiteAllInfo siteAllInfo=footfallGlobalService.selectSiteByUserId(userInfo,siteType);
		String siteID="";
		if(siteId!=null&& !siteId.equals("")){
			siteID=siteId;
		}else{
			model.addAttribute("datetime", footfallGlobalService.getDate());
			Language lang = Lang.getInfo(sysLang);
			model.addAttribute("lang",lang);
			String menuHtml = loginService.getMenuHtml(userInfo, "comparativeAnalysis");
			model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
			return "comparativeAnalysis";
		}
		
		siteId = siteID;
		
		 /**初始化指标权限*/
        List<String> siteTypes = footfallGlobalService.getSiteTypes(siteId);
        /**获取用户指标权限*/
        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
      //数据分析-对比分析 model为2_1
        String moduleId = FootfallConstant.COMPARATIVE;
        /**指标为场所指标和用户指标交集*/
        //获取趋势分析指标
        List<String> indexList = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId, siteTypes);
        //取趋势分析指标分组
        HashMap<String, List<String>> indexListOfGroup = footfallGlobalService.getIndexListOfGroup(indexList);
        model.addAttribute("indexList",JSONObject.fromObject(indexListOfGroup));
        
      //获取排行榜各时间指标
        HashMap<String, Object> dateIndexMap = new HashMap<String, Object>();
        List<String> indexHour  = footfallGlobalService.getTimeIndex("hour");
        dateIndexMap.put("indexHour", indexHour);
        List<String> indexDay  = footfallGlobalService.getTimeIndex("day");
        dateIndexMap.put("indexDay", indexDay);
        List<String> indexWeek  = footfallGlobalService.getTimeIndex("week");
        dateIndexMap.put("indexWeek", indexWeek);
        List<String> indexMonth  = footfallGlobalService.getTimeIndex("month");
        dateIndexMap.put("indexMonth", indexMonth);
        List<String> indexYear  = footfallGlobalService.getTimeIndex("year");
        dateIndexMap.put("indexYear", indexYear);
        model.addAttribute("dateIndexMap",JSONObject.fromObject(dateIndexMap));

        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
        model.addAttribute("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
        model.addAttribute("indexInfo",JSONObject.fromObject(indexInfo));
        /**初始化全局分析的指标权限结束*/
        
        
        
		
		if(siteID!=null&& !siteID.equals("")){
			model.addAttribute("siteId", siteID);
			model.addAttribute("datetime", footfallGlobalService.getDate());
		}
		model.addAttribute("buttonExport",buttonExport);
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang",lang);
		String menuHtml = loginService.getMenuHtml(userInfo, "comparativeAnalysis");
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		return "comparativeAnalysis";
	}
		
	
	/**前台获取图表数据  */
	@RequestMapping("/getComparativeAnalysis")
	@ResponseBody
	public HashMap<String , Object> getGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
//		StringBuffer name1=request.get
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		
		String siteIdStr=request.getParameter("siteIds");//获取几天的数据
		String[] siteIds =siteIdStr.split(",");
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		//查询图表
		List<HashMap<String, Object>> resultList=new ArrayList<HashMap<String, Object>>();
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("userInfo", userInfo);
		
		List<String> siteNames =  new ArrayList<String>();//导航栏地址
		List<ReportGraphData> listNames = new ArrayList<ReportGraphData>() ;
		for(int n=0;n<siteIds.length;n++){
			if(!"".equals(siteIds[n])){
				siteNames.add(footfallGlobalService.getSiteNames(siteIds[n]));//导航栏地址
			}
			paraMap.put("siteId", siteIds[n]);
			List<ReportGraphData> list= footfallGlobalService.getGraphData(paraMap);
			listNames = list;
			String siteName=footfallGlobalService.getSiteName(siteIds[n]);
			HashMap<String, Object> map=new HashMap<String, Object>();
			map.put("data",list);
			map.put("siteId",siteIds[n]);
			map.put("siteName",siteName);
			resultList.add(map);
			
			
		}
		//报表数据说明
		String sitenames = "";
		if("hour".equals(timeType_table)){
			paraMapResult.put("stadubiao", listNames.get(0).getDate());
//			paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getDatatime());
		}else if("day".equals(timeType_table)){
			paraMapResult.put("stadubiao", listNames.get(0).getDatatime());
			paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getDatatime());
		}else if("week".equals(timeType_table)){
			paraMapResult.put("stadubiao", listNames.get(0).getYear()+"-"+listNames.get(0).getWeek());
			paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear()+"-"+listNames.get(listNames.size()-1).getWeek());
		}else if("month".equals(timeType_table)){
			paraMapResult.put("stadubiao", listNames.get(0).getYear()+"-"+listNames.get(0).getMonth());
			paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear()+"-"+listNames.get(listNames.size()-1).getMonth());
		}else{
			paraMapResult.put("stadubiao", listNames.get(0).getYear());
			paraMapResult.put("endtubiao", listNames.get(listNames.size()-1).getYear());
		}
		if(siteNames.size()<4){
			for(String sitename:siteNames){
				sitenames = sitenames +sitename+'，';
			}
			if(!"".equals(sitenames)){
				sitenames = sitenames.substring(0, sitenames.length()-1);
			}
		}else{
			int i = 0;
			for(String sitename:siteNames){
				if(i>=3){
					break;
				}
				sitenames = sitenames +sitename+'，';
				i++;
			}
			sitenames = sitenames.substring(0, sitenames.length()-1);
			sitenames = sitenames+"．．．";
		}
		
		String siteTypeNames = "";
		
		/**
		 *  跟广场类型
		String[] siteidstr = siteIdStr.split(",");
		for(String siteid:siteidstr){
			String siteName = footfallGlobalService.getSiteNames(siteid);
			List<String> siteType = footfallGlobalService.getSiteTypes(siteid);
			//获取siteId 的场所类型中文名称
			String siteTypeName = "";
			if(siteType!=null&&!"".equals(siteType)){
				String siteType1 = siteType.get(0);
				siteTypeName = footfallGlobalService.getSiteTypeName(Integer.parseInt(siteType1));
			}
			siteTypeNames = siteTypeNames + siteName+"（"+siteTypeName+"）"+"&";
		}
		siteTypeNames = siteTypeNames.substring(0, siteTypeNames.length()-1);
		*/
		String[] siteidstr = siteIdStr.split(",");
		for(String siteid:siteidstr){
			String siteName = footfallGlobalService.getSiteNames(siteid);
			List<String> siteType = footfallGlobalService.getSiteTypes(siteid);
			//获取siteId 的场所类型中文名称
			String siteTypeName = "";
			if(siteType!=null&&!"".equals(siteType)){
				String siteType1 = siteType.get(0);
				siteTypeName = footfallGlobalService.getSiteTypeName(Integer.parseInt(siteType1));
			}
			siteTypeNames = siteTypeNames + siteName+"&";
		}
		siteTypeNames = siteTypeNames.substring(0, siteTypeNames.length()-1);
		
		paraMapResult.put("siteTypeNames", siteTypeNames);
		
		paraMapResult.put("siteN", sitenames);
		//插入数据日期类型，日周年月
		paraMapResult.put("timeType_table",timeType_table);
		//插入折线数据
		paraMapResult.put("result", resultList);
		//获取表格数据
		StringBuffer loadTable = footfallGlobalService.getGlobalTable(resultList,timeType_table,type);
		paraMapResult.put("loadTable", loadTable);
		
		return paraMapResult;
	}
	
	/**前台的siteId获取siteName  */
	@RequestMapping("/getComparativeSiteName")
	@ResponseBody
	public List<HashMap<String , String>> getSiteName(HttpServletRequest request,HttpServletResponse response) throws Exception {
		List<HashMap<String , String>> resultList=new ArrayList<HashMap<String,String>>();
		//图表的开始时间
		String siteIdStr=request.getParameter("siteIds");//获取几天的数据
		String[] siteIds =siteIdStr.split(",");
		for(int n=0;n<siteIds.length;n++){
		HashMap<String , String> temMap=new HashMap<String, String>();
		String siteid=siteIds[n];
		String siteName = footfallGlobalService.getSiteName(siteIds[n]);
		temMap.put("siteId", siteid);
		temMap.put("siteName", siteName);
		resultList.add(temMap);
		
		}
		return resultList;
		
	}
	

}
